package com.quyang.voice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyang.voice.mapper.LitemallOrderMapper;
import com.quyang.voice.model.*;
import com.quyang.voice.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class LitemallOrderServiceImpl extends ServiceImpl<LitemallOrderMapper, LitemallOrder>
    implements LitemallOrderService{

    public static final Short STATUS_CREATE = 101;
    public static final Short STATUS_PAY = 201;
    public static final Short STATUS_SHIP = 301;
    public static final Short STATUS_CONFIRM = 401;
    public static final Short STATUS_CANCEL = 102;
    public static final Short STATUS_AUTO_CANCEL = 103;
    public static final Short STATUS_ADMIN_CANCEL = 104;
    public static final Short STATUS_REFUND = 202;
    public static final Short STATUS_REFUND_CONFIRM = 203;
    public static final Short STATUS_AUTO_CONFIRM = 402;

    @Autowired
    ICustAccountbaseService custAccountbaseService;

    @Autowired
    private IAppConfigService appConfigService;


    @Autowired
    LitemallOrderService orderService;
    @Autowired
    IConsumeRecordService consumeRecordService;



    @Autowired
    IMissuUsersService missuUsersService;

    @Autowired
    ShopkeeperService shopkeeperService;

    //    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class},propagation = Propagation.REQUIRES_NEW)
    public Boolean PayOrder(String orderSn){
        AppConfig appConfig = appConfigService.getById(1);

        Double handlingFee =   appConfig.getIntegralServiceCharge() + appConfig.getRecommendServiceCharge() + appConfig.getSystemServiceCharge();
//        Double handlingFee =  appConfig.getShopServiceCharge() + appConfig.getIntegralServiceCharge() + appConfig.getRecommendServiceCharge() + appConfig.getSystemServiceCharge();


//        try {

        List<LitemallOrder> orderList = list(new QueryWrapper<LitemallOrder>().eq("order_all_sn", orderSn));
        Integer userId = orderList.get(0).getUserId();
        //判断余额是否足够
        QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
        custAccountbaseQueryWrapper.eq("user_id",orderList.get(0).getUserId());
        CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);

//        List<LitemallOrder> orderList = orderService.findByOrderAllSn(orderSn);

        //组合订单
        if (orderList.size() > 0){
            BigDecimal integrals = new BigDecimal(0);
            BigDecimal amounts = new BigDecimal(0);
            for (LitemallOrder order: orderList
            ) {
                if (order.getStatus()){
                    integrals = integrals.add( order.getActualPrice());
                }else {
                    amounts = amounts.add( order.getActualPrice());
                }
            }
            if (custAccountbase.getIntegral().compareTo(integrals.doubleValue())  == -1 ){
//                return ResponseUtil.fail(500,"积分不足");
                return false;
            }


            for (LitemallOrder order: orderList
            ) {
                //判断商品是不是积分商品

                QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper2 = new QueryWrapper<>();
                custAccountbaseQueryWrapper2.eq("user_id",order.getShopId());
                CustAccountbase custAccountbase2 = custAccountbaseService.getOne(custAccountbaseQueryWrapper2);
                if (custAccountbase2 == null){
                    custAccountbase2 = new CustAccountbase();
                    custAccountbase2.setUserId(order.getShopId().longValue());
                    custAccountbase2.setFrozen(0.00);
                    custAccountbase2.setIntegralFrozen(0.00);
                    custAccountbase2.setAmount(0.00);
                    custAccountbase2.setIntegral(0.00);
                    custAccountbaseService.save(custAccountbase2);
                }


                BigDecimal actualPrice = order.getOrderPrice();

                BigDecimal amount = new BigDecimal(custAccountbase.getAmount());
                //积分余额
                BigDecimal integral = new BigDecimal(custAccountbase.getIntegral());





                if (order.getStatus()){
                    if (integral.compareTo(actualPrice)  == -1 ){
//                        return ResponseUtil.fail(500,"积分不足");
                        return false;
                    }

                    custAccountbase.setIntegral(integral.subtract(actualPrice).doubleValue());
                    custAccountbaseService.updateById(custAccountbase);

                    custAccountbase2.setIntegral(custAccountbase2.getIntegral() + actualPrice.doubleValue());
                    custAccountbaseService.updateById(custAccountbase2);


                }else {
//                    if (amount.compareTo(actualPrice)  == -1 ){
//                        return ResponseUtil.fail(500,"余额不足");
//                    }
//                    custAccountbase.setAmount(amount.subtract(actualPrice).doubleValue());
                    BigDecimal add = new BigDecimal(custAccountbase.getIntegralFrozen().toString()).add(order.getOrderPrice().multiply(new BigDecimal(appConfig.getIntegralServiceCharge().toString())));
                    custAccountbase.setIntegralFrozen( add.doubleValue() );
                    custAccountbaseService.updateById(custAccountbase);



                    //增加商家的余额
                    BigDecimal amount2 = new BigDecimal(custAccountbase2.getAmount());
                    //手续费
                    BigDecimal subtract = actualPrice.subtract(actualPrice.multiply(new BigDecimal(handlingFee)));


                    custAccountbase2.setFrozen(custAccountbase2.getFrozen() + subtract.doubleValue());
                    custAccountbaseService.updateById(custAccountbase2);
                }



                //        平台店铺  只需要减去相应金额
                //记录买家的
                ConsumeRecord consumeRecord1 = new ConsumeRecord();

                consumeRecord1.setUserId(userId.longValue());
                consumeRecord1.setTradeNo(orderSn.toString());
                consumeRecord1.setToUserId(order.getShopId().longValue());

                consumeRecord1.setType(order.getStatus()? 21:20);
//                consumeRecord1.setTradeNo(RandomUtil.randomString(12));
//                actualPrice.subtract(actualPrice.multiply(new BigDecimal(appConfig.getShopServiceCharge().toString()))).doubleValue();
                consumeRecord1.setMoney(actualPrice.subtract(actualPrice.multiply(new BigDecimal(appConfig.getShopServiceCharge().toString()))).doubleValue());
                consumeRecord1.setChangeType(2);
                consumeRecord1.setStatus(0);
                consumeRecord1.setTime(new Date());
                consumeRecord1.setPayType(2);
                consumeRecord1.setDescs("购买商品");
                consumeRecord1.setCurrentBalance(order.getStatus()? custAccountbase.getIntegral():custAccountbase.getAmount());
                consumeRecord1.setOperationAmount(actualPrice.doubleValue());
                consumeRecord1.setShopServiceCharge(appConfig.getShopServiceCharge());
                consumeRecord1.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                consumeRecord1.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                consumeRecord1.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                consumeRecordService.save(consumeRecord1);

                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_id",order.getShopId());
                Shopkeeper shopkeeper = shopkeeperService.getOne(wrapper);

                //记录卖家的
                ConsumeRecord consumeRecord2 = new ConsumeRecord();
                consumeRecord2.setUserId(order.getShopId().longValue());
                consumeRecord2.setTradeNo(orderSn.toString());
                consumeRecord2.setToUserId(userId.longValue());
                consumeRecord2.setServiceCharge(handlingFee);
                consumeRecord2.setType(order.getStatus()? 23:22);
//                consumeRecord2.setTradeNo(RandomUtil.randomString(12));

                BigDecimal subtract = order.getOrderPrice().subtract(order.getOrderPrice().multiply(new BigDecimal(handlingFee.toString())));
                if (shopkeeper.getIsVip()){
                    consumeRecord2.setMoney(subtract.doubleValue() - (subtract.doubleValue() * appConfig.getSpecificShare()));
                }else {
                    consumeRecord2.setMoney(subtract.doubleValue());
                }

                consumeRecord2.setChangeType(1);
                consumeRecord2.setStatus(0);
                consumeRecord2.setPayType(1);
                consumeRecord2.setDescs("商品出售");
                consumeRecord2.setTime(new Date());
                if (order.getStatus()) {
                    consumeRecord2.setCurrentBalance(custAccountbase2.getIntegral());
                } else{
                    consumeRecord2.setCurrentBalance(custAccountbase2.getAmount());
                }
                consumeRecord2.setOperationAmount(actualPrice.doubleValue() - actualPrice.doubleValue() *handlingFee );
                consumeRecord2.setShopServiceCharge(appConfig.getShopServiceCharge());
                consumeRecord2.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                consumeRecord2.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                consumeRecord2.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                consumeRecordService.save(consumeRecord2);



                if ( !order.getStatus()) {

                    //记录平台抽成
                    ConsumeRecord consumeRecord5 = new ConsumeRecord();
                    consumeRecord5.setUserId(order.getShopId().longValue());
                    consumeRecord5.setTradeNo(orderSn.toString());
                    consumeRecord5.setToUserId(0L);
                    consumeRecord5.setServiceCharge(handlingFee);
                    consumeRecord5.setType(25);
//                    consumeRecord5.setTradeNo(RandomUtil.randomString(12));
                    consumeRecord5.setMoney(order.getOrderPrice().multiply(new BigDecimal(handlingFee.toString())).doubleValue());
                    consumeRecord5.setChangeType(2);
                    consumeRecord5.setStatus(0);
                    consumeRecord5.setPayType(1);
                    consumeRecord5.setDescs("平台抽成");
                    consumeRecord5.setTime(new Date());
                    consumeRecord5.setOperationAmount(actualPrice.doubleValue() );
                    consumeRecord5.setCurrentBalance(order.getStatus()?custAccountbase2.getIntegral():custAccountbase2.getShopAmount());
                    consumeRecord5.setShopServiceCharge(appConfig.getShopServiceCharge());
                    consumeRecord5.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                    consumeRecord5.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                    consumeRecord5.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                    consumeRecordService.save(consumeRecord5);

                    if (shopkeeper.getIsVip()){
                        //记录平台抽成
                        consumeRecord5 = new ConsumeRecord();
                        consumeRecord5.setUserId(order.getShopId().longValue());
                        consumeRecord5.setTradeNo(orderSn.toString());
                        consumeRecord5.setToUserId(0L);
                        consumeRecord5.setServiceCharge(handlingFee);
                        consumeRecord5.setType(51);
//                    consumeRecord5.setTradeNo(RandomUtil.randomString(12));
                        consumeRecord5.setMoney(subtract.doubleValue() * appConfig.getSpecificShare());
                        consumeRecord5.setChangeType(2);
                        consumeRecord5.setStatus(0);
                        consumeRecord5.setPayType(1);
                        consumeRecord5.setDescs("联盟分成");
                        consumeRecord5.setTime(new Date());
                        consumeRecord5.setOperationAmount(actualPrice.doubleValue() );
                        consumeRecord5.setCurrentBalance(order.getStatus()?custAccountbase2.getIntegral():custAccountbase2.getShopAmount());
                        consumeRecord5.setShopServiceCharge(appConfig.getShopServiceCharge());
                        consumeRecord5.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                        consumeRecord5.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                        consumeRecord5.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                        consumeRecordService.save(consumeRecord5);

                    }



                    //
                    //记录买家的 获得积分
                    ConsumeRecord consumeRecord6 = new ConsumeRecord();
                    consumeRecord6.setUserId(userId.longValue());
                    consumeRecord6.setTradeNo(orderSn.toString());
                    consumeRecord6.setToUserId(order.getShopId().longValue());

                    consumeRecord6.setType(order.getStatus()? 21:20);
//                    consumeRecord6.setTradeNo(RandomUtil.randomString(12));
                    consumeRecord6.setMoney(order.getOrderPrice().doubleValue() * appConfig.getIntegralServiceCharge());
                    consumeRecord6.setChangeType(1);
                    consumeRecord6.setStatus(0);
                    consumeRecord6.setPayType(1);
                    consumeRecord6.setTime(new Date());
                    consumeRecord6.setDescs("积分获得");
                    consumeRecord6.setCurrentBalance(custAccountbase.getIntegralFrozen() + actualPrice.doubleValue() * appConfig.getIntegralServiceCharge());
                    consumeRecord6.setOperationAmount(actualPrice.doubleValue() * appConfig.getIntegralServiceCharge());
                    consumeRecord6.setShopServiceCharge(appConfig.getShopServiceCharge());
                    consumeRecord6.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                    consumeRecord6.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                    consumeRecord6.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                    consumeRecordService.save(consumeRecord6);


                }






                //最后查询一下该用户的上级


                MissuUsers missuUsers = missuUsersService.getById(userId);


                //记录平台回报
                ConsumeRecord consumeRecord9 = new ConsumeRecord();
                consumeRecord9.setUserId(0L);
                consumeRecord9.setTradeNo(order.getOrderSn());
                consumeRecord9.setToUserId(order.getShopId().longValue());
                consumeRecord9.setServiceCharge(appConfig.getSystemServiceCharge());
                consumeRecord9.setType(28);

                consumeRecord9.setChangeType(1);
                consumeRecord9.setStatus(0);
                consumeRecord9.setDescs("平台回报");
                consumeRecord9.setTime(new Date());

                //如果没有推荐分成  平台抽取
                if (StrUtil.isBlankIfStr(missuUsers.getReCommunicationNumber())){
                    consumeRecord9.setOperationAmount(order.getOrderPrice().doubleValue() * (appConfig.getSystemServiceCharge() + appConfig.getRecommendServiceCharge() ));
                }else {
                    consumeRecord9.setOperationAmount(order.getOrderPrice().doubleValue() * appConfig.getSystemServiceCharge() );
                }

                consumeRecord9.setMoney(consumeRecord9.getOperationAmount());

                consumeRecord9.setShopServiceCharge(appConfig.getShopServiceCharge());
                consumeRecord9.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                consumeRecord9.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                consumeRecord9.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                consumeRecord9.setPayType(3);
                consumeRecordService.save(consumeRecord9);




                if (!StrUtil.isBlankIfStr(missuUsers.getReCommunicationNumber())){
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("my_communication_number",missuUsers.getReCommunicationNumber());
                    MissuUsers one = missuUsersService.getOne(queryWrapper);

                    CustAccountbase custAccountbase3 = custAccountbaseService.getOne(new QueryWrapper<CustAccountbase>().eq("user_id", one.getUserUid()));
                    if (custAccountbase3 == null){
                        custAccountbase3 = new CustAccountbase();
                        custAccountbase3.setFrozen(order.getActualPrice().doubleValue() * appConfig.getRecommendServiceCharge());
                        custAccountbase3.setUserId(one.getUserUid().longValue());
                        custAccountbaseService.save(custAccountbase3);
                    }else {

                        custAccountbase3.setFrozen(custAccountbase3.getFrozen() + order.getOrderPrice().doubleValue()* appConfig.getRecommendServiceCharge());
                        custAccountbaseService.updateById(custAccountbase3);

                    }

                    //记录推荐分成的
                    ConsumeRecord consumeRecord3 = new ConsumeRecord();
                    consumeRecord3.setUserId(one.getUserUid().longValue());
                    consumeRecord3.setTradeNo(orderSn.toString());
                    consumeRecord3.setToUserId(userId.longValue());
                    consumeRecord3.setServiceCharge(handlingFee);
                    consumeRecord3.setType(24);
//                    consumeRecord3.setTradeNo(RandomUtil.randomString(12));
                    consumeRecord3.setMoney(order.getOrderPrice().doubleValue() * appConfig.getRecommendServiceCharge());
                    consumeRecord3.setChangeType(1);
                    consumeRecord3.setStatus(0);
                    consumeRecord3.setPayType(1);
                    consumeRecord3.setTime(new Date());
                    consumeRecord3.setShopServiceCharge(appConfig.getShopServiceCharge());
                    consumeRecord3.setIntegralServiceCharge(appConfig.getIntegralServiceCharge());
                    consumeRecord3.setRecommendServiceCharge(appConfig.getRecommendServiceCharge());
                    consumeRecord3.setSystemServiceCharge(appConfig.getSystemServiceCharge());
                    consumeRecord3.setDescs("商品分成");
                    consumeRecord3.setCurrentBalance(custAccountbase3.getFrozen() + actualPrice.doubleValue() * appConfig.getRecommendServiceCharge());

                    consumeRecord3.setOperationAmount(actualPrice.doubleValue() * appConfig.getRecommendServiceCharge());
                    consumeRecordService.save(consumeRecord3);


                }





//
//                    // 设置订单状态
                order.setOrderStatus(STATUS_PAY);
                order.setEndTime(LocalDateTime.now());
//                    order.setUpdateTime(LocalDateTime.now());
//                    order.setConsignee(checkedAddress.getName());
//                    order.setMobile(checkedAddress.getTel());
//
//                    String detailedAddress = checkedAddress.getProvince() + checkedAddress.getCity() + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
//                    order.setAddress(detailedAddress);

                if (!orderService.updateById(order)) {
                    throw new RuntimeException("更新数据已失效");
                }


            }

            //单一订单
        }
//        } catch (Exception e) {
//            TransactionAspectSupport.
//                    currentTransactionStatus().setRollbackOnly();
//        }


        return true;
    }

}




